<template>
  <basic-container class="app-container">
    <div class="filter_container">
      <el-form :inline="true" :model="refundFrom">
        <el-form-item label="退款状态">
          <XmSelect :options="statusSelection" :config="{ valueKey: 'dictKey', labelKey: 'dictValue' }"
            ref="whetherRefundRef" v-model="refundFrom.whetherRefund" clearable placeholder="退款状态" size="small"
            style="width: 120px" @change="handleRefundStatusChange">
          </XmSelect>
        </el-form-item>
        <el-form-item label="渠道类别">
          <ChannelTypeSelect ref="ChannelTypeSelect" v-model="refundFrom.channelTypeId" class="w-120" size="small" @change="refundFrom.channelId = ''" clearable></ChannelTypeSelect>
        </el-form-item>
        <el-form-item label="渠道">
          <ChannelSelect ref="ChannelSelect" v-model="refundFrom.channelId" class="w-120" size="small" @visible-change="getchannelList" filterable clearable></ChannelSelect>
        </el-form-item>
        <el-form-item label="后台单号">
          <el-input v-model.trim="refundFrom.xmbzNo" size="small" clearable placeholder="请输入后台单号"></el-input>
        </el-form-item>
        <el-form-item label="平台单号">
          <el-input v-model.trim="refundFrom.platformNo" size="small" clearable placeholder="请输入平台单号"></el-input>
        </el-form-item>
        <el-form-item label="操作人">
          <el-input v-model.trim="refundFrom.operator" size="small" clearable placeholder="请输入操作人"></el-input>
        </el-form-item>
        <el-form-item label="创建退款时间">
          <el-date-picker size="small" v-model="Launchdate" type="datetimerange" range-separator="至"
            start-placeholder="开始时间" end-placeholder="结束时间" :default-time="['00:00:00', '23:59:59']"
            value-format="yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm" :clearable="refundFrom.whetherRefund == 2"></el-date-picker>
        </el-form-item>
        <el-form-item label="退款等级">
          <RefundLevelSelect class="w-120" size="small" v-model="refundFrom.refundGrade" clearable></RefundLevelSelect>
        </el-form-item>
        <el-form-item label="退款二维码">
          <XmSelect :options="refundCodeList" v-model="refundFrom.isRefundCode" clearable size="small"
            style="width: 120px" placeholder="退款二维码" @change="onChangeRefundCode">
          </XmSelect>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="handleFilterRefund(Launchdate)" size="small"
            icon="el-icon-search">查询</el-button>
          <el-button type="success" plain @click="handleAddRefund" size="small"
            icon="el-icon-circle-plus-outline">新建</el-button>
          <el-button type="warning" plain @click="handleAllRefund" size="small">一键退款</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div>
      <XmTable :config="tableConfig" class="table" ref="table" :noWatchParams="getParams()" :height="tableHeight">
        <el-table-column slot="column-check" type="selection" width="55" fixed="left">
        </el-table-column>
        <template slot="column-refundGradeName" slot-scope="{data}">
          <div>
            <el-tag type="danger" v-if="data.remind == '2'" class="d-b mb-5 ta-c" size="mini">催办</el-tag>
            <el-tag :type="levelTypeMap[data.refundGrade]" class="d-b mb-5 ta-c" size="mini">{{ data.refundGradeName
            }}</el-tag>
          </div>
        </template>
        <template slot="column-refundDetails" slot-scope="{data}">
          <div v-if="data.refundDetails && data.refundDetails.length">
            <el-button class="mg-5" type="primary" size="mini" @click="handleEditMulRefund(data)">修改退款信息</el-button>
            <div v-for="(refundItem, i) in data.refundDetails" class="c-red fw-bold refund-item" :key="i">{{ refundItem }}
            </div>
          </div>
        </template>
        <template slot="column-whetherRefundName" slot-scope="{data}">
          <el-tag :type="statusTypeMap[data.whetherRefund]">{{ data.whetherRefundName }}</el-tag>
        </template>
        <template slot="column-goodsName" slot-scope="{data}">
          <div>
            <div class="sub-goods-item">{{ data.goodsName }}</div>
            <div v-if="data.suborderList && data.suborderList.length">
              <div class="sub-goods-item" v-for="(item, index) in data.suborderList" :key="index">
                <span>{{ item.goodsName }} </span>
                <span class="ml-5 c-red">（子单）</span>
                <span v-if="item.tyingProduct" class="ml-5 c-red">（已退{{ item.tyingProduct }}）</span>
              </div>
            </div>
          </div>
        </template>
        <template slot="column-totalPrice" slot-scope="{data}">
          <div class="c-red fw-bold fz-16">{{ data.refundMoney + data.cakeCompensatePrice + data.sincerityGold }}</div>
        </template>
        <template slot="column-refundCode" slot-scope="{data}">
          <imageView class="w-200 h-200" v-if="data.refundCode" :src="data.refundCode"></imageView>
        </template>
        <template slot="column-operate" slot-scope="{data}">
          <el-button class="d-b" type="primary" size="mini" @click="handleEdit(data, 1)">
            编辑
          </el-button>
          <el-button size="mini" @click="handleViewLog(data)" class="ml-0 mt-5">
            日志
          </el-button>
          <el-button v-show="data.whetherRefund == 2" type="success" size="mini" @click="handleRefund(data)"
            class="ml-0 mt-5">
            标记退款
          </el-button>
          <el-button v-show="data.whetherRefund == 2" type="danger" size="mini" @click="handleBackRefund(data)"
            class="ml-0 mt-5">
            驳回退款
          </el-button>
        </template>
      </XmTable>
    </div>

    <addRefundDialog ref="addRefundDialog" @submit="getWorkOrderList"></addRefundDialog>
    <editRefundDialog ref="editRefundDialog" @submit="getWorkOrderList"></editRefundDialog>
    <orderLogDialog ref="orderLogDialog"></orderLogDialog>
    <againRefundDialog ref="againRefundDialog" :showGoods="false" @confirm="handleMulRefundConfirm"></againRefundDialog>
  </basic-container>
</template>

<script>
import {
  //接口
  signWorkOrderRefund, //标记已退款
  getFinancialRejection, //  财务驳回
  getWhetherRefundList, //退款状态列表
  batchSignWorkOrderRefund
} from "@/api/workorder";
import againRefundDialog from '@/components/order-detail/components/againRefundDialog'
import { tableConfig } from './config'
import addRefundDialog from "./components/addRefundDialog";
import editRefundDialog from "./components/editRefundDialog";
import orderLogDialog from '@/components/dialog/orderLogDialog';
import imageView from '@/components/image/imageView'

const refundCodeList = [{
  label: '有退款码',
  value: '1',
}, {
  label: '无退款码',
  value: '0',
}]

const levelTypeMap = {
  1: 'info',
  2: 'primary',
  3: 'warning',
  4: 'danger',
}

const statusTypeMap = {
  1: 'success',
  2: 'danger',
}

export default {
  components: {
    addRefundDialog,
    editRefundDialog,
    orderLogDialog,
    againRefundDialog,
    imageView
  },
  data() {
    const height = document.documentElement.clientHeight
    const tableHeight = height - 300
    return {
      tableConfig,
      refundCodeList,
      levelTypeMap,
      statusTypeMap,
      refundFrom: {
        xmbzNo: "", //后台单号
        operator: "", //操作人
        platformNo: "", //平台单号
        approvalPass: 2, //审批是否通过  0:否 1:是
        whetherRefund: "", //退款状态 1:已退款 2:未退款
        refundGrade: "", //退款等级 1:一般 2:中等 3:紧急 4:非常紧急
        channelId: "", // 渠道
        channelTypeId: "", //渠道列表
        workOrderStartTime: this.dayjs(new Date())
          .format("YYYY-MM-DD 00:00:00")
          .toString(), //配送开始时间
        workOrderEndTime: this.dayjs(new Date())
          .format("YYYY-MM-DD 23:59:59")
          .toString(), //配送结束时间
        isRefundCode: '',
      },
      Launchdate: [
        this.dayjs(new Date())
          .format("YYYY-MM-DD 00:00"),
        this.dayjs(new Date())
          .format("YYYY-MM-DD 23:59"),
      ],
      statusSelection: [], //退款 状态
      tableHeight: tableHeight,
    };
  },
  methods: {
    // 选择框回车失焦
    selectBlur(e) {
      if (e.keyCode == 13) {
        this.$refs["whetherRefundRef"].blur();
        this.$refs["channelTypeidNameRef"].blur();
        this.$refs["channelNameRef"].blur();
        this.$refs["refundGradeNameRef"].blur();
        e.returnValue = false;
      }
    },
    keyupEnter() {
      if (window.event.keyCode == 13) {
        this.handleFilterRefund(this.Launchdate); // 查询事件
      }
    },
    getstatusList() {
      getWhetherRefundList("").then(response => {
        this.statusSelection = response.data.data;
      });
    },
    handleRefundStatusChange(status) {
      if (status == 2) {
        this.Launchdate = []
      } else {
        if (!this.Launchdate || !this.Launchdate.length) {
          this.Launchdate = [
            this.dayjs(new Date()).format("YYYY-MM-DD 00:00"),
            this.dayjs(new Date()).format("YYYY-MM-DD 23:59")
          ]
        }
      }
      this.getWorkOrderList();
    },
    handleFilterRefund(times) {
      //退款查询
      if (times && times.length) {
        var start = Date.parse(this.dayjs(times[0]).format("YYYY-MM-DD HH:mm:ss"));
        var end = Date.parse(this.dayjs(times[1]).format("YYYY-MM-DD HH:mm:ss"));
        //讲两个时间相减，求出相隔的天数
        var dayCount = Math.abs(end - start) / 1000 / 60 / 60 / 24;
        if (dayCount > 31) {
          this.$message({
            showClose: true,
            message: "时间间隔不可超过31天",
            type: "warning"
          });
          return
        }
      }

      this.getWorkOrderList();
    },
    getWorkOrderList() {
      this.$nextTick(() => {
        this.$refs.table.fetch()
      })
    },
    getParams() {
      const [start, end] = this.Launchdate || []
      const params = {
        ...this.refundFrom,
        workOrderStartTime: start ? this.dayjs(start).format('YYYY-MM-DD HH:mm:00') : undefined,
        workOrderEndTime: end ? this.dayjs(end).format('YYYY-MM-DD HH:mm:59') : undefined,
      }
      return params
    },
    getchannelList() {
      //渠道
      if (!this.refundFrom.channelTypeId) {
        this.$message({
          type: "warning",
          message: "请先选择渠道类别!"
        });
        return false;
      } else {
        const ChannelTypeItem = this.$refs.ChannelTypeSelect.getSelectedItem();
        this.$refs.ChannelSelect.getList(ChannelTypeItem.id)
      }
    },
    onChangeRefundCode() {
      this.getWorkOrderList()
    },
    handleAddRefund() {
      this.$refs.addRefundDialog.show()
    },
    handleAllRefund() {
      const list = this.$refs.table.getSelection()
      if (list && list.length) {
        this.$confirm(`请确认是否退款所选订单?【${list.map(item => item.xmbzNo).join('，')}】`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          batchSignWorkOrderRefund(list.map(item => item.id)).then(res => {
            if (res.data.code === 200) {
              this.$message({
                type: 'success',
                message: '操作成功！'
              })
              this.getWorkOrderList()
            }
          })
        })
      } else {
        this.$message({
          type: 'warning',
          message: '请先选择记录！'
        })
      }
    },
    handleEdit(data) {
      this.$refs.editRefundDialog.show({ data })
    },
    handleViewLog(data) {
      this.$refs.orderLogDialog.show({ orderId: data.orderId })
    },
    // 标记退款
    handleRefund(item) {
      //财务标记已退款
      this.$confirm("确定财务标记已退款？, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          signWorkOrderRefund({
            id: item.id,
            orderId: item.orderId,
            orderDetailId: item.orderDetailId
          }).then(() => {
            this.$message({
              type: "success",
              message: "财务标记已退款成功!"
            });
            this.getWorkOrderList();
          });
        })
    },
    // 驳回退款
    handleBackRefund(item) {
      // 财务驳回
      this.$prompt("请输入驳回原因", "财务驳回", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(({ value }) => {
          getFinancialRejection({
            id: item.id,
            orderId: item.orderId,
            notPassReason: value
          }).then(() => {
            this.$message({
              type: "success",
              message: "驳回原因: " + value
            });
            this.getWorkOrderList();
          });

        })
    },
    // 修改多次退款信息
    handleEditMulRefund(item) {
      this.$refs.againRefundDialog.show({
        detail: {
          workRefundId: item.id
        },
        order: {
          id: item.orderId,
          xmbzNo: item.xmbzNo
        },
        type: item.refundNotReturn == '退款不退货' ? 1 : 0
      })
    },
    handleMulRefundConfirm() {
      this.getWorkOrderList();
    },
  },
  mounted() {
    this.getstatusList()
    window.addEventListener("keydown", this.keyupEnter);
  }
};
</script>
<style lang="scss" scoped>
.sub-goods-item,
.refund-item {
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 2px 4px;
  margin: 5px;
  display: inline-block;
}
</style>